package com.yulebaby.callsenter.global;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Author: Zhangbo
 * Time: 2016年11月8日
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    public static final String LOG_FOLDER = "yulebaby";

    private static CrashHandler instance;
    private Context mCtx;

    public static CrashHandler getInstance() {
        if (instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        saveExceptionLog(ex);
        android.os.Process.killProcess(android.os.Process.myPid());

    }

    public void init(Context ctx) {
        mCtx = ctx;
    }

    /**
     * 机器信息
     */
    private String collectDeviceInfo(Context mCtx) {

        StringBuilder builder = new StringBuilder();
        TelephonyManager tm = (TelephonyManager) mCtx.getSystemService(Context.TELEPHONY_SERVICE);
        builder.append("\nMode = " + Build.MODEL);
        builder.append("\nReleaseMode = " + Build.VERSION.RELEASE);
        builder.append("\nDeviceId = " + tm.getDeviceId());
        builder.append("\nDeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());
        builder.append("\nLine1Number = " + tm.getLine1Number());
        builder.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());
        builder.append("\nNetworkOperator = " + tm.getNetworkOperator());
        builder.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());
        return builder.toString();
    }


    /**
     * 保存日志
     */
    private void saveExceptionLog(Throwable ex) {
        String logdir;
        if (Environment.getExternalStorageDirectory() != null) {
            logdir = App.FILE_BASE_PATH + File.separator + "Crash_Log";
            File file = new File(logdir);
            boolean mkSuccess;
            if (!file.isDirectory()) {
                mkSuccess = file.mkdirs();
                if (!mkSuccess) {
                    mkSuccess = file.mkdirs();
                }
            }
            try {
                String deviceInfo = collectDeviceInfo(mCtx);
                FileWriter fw = new FileWriter(logdir + File.separator + generationCrashLogName(), true);
                fw.write(new Date() + "\n");
                fw.write(deviceInfo + "\n");
                StackTraceElement[] stackTrace = ex.getStackTrace();
                fw.write(ex.getMessage() + "\n");
                for (int i = 0; i < stackTrace.length; i++) {
                    fw.write(stackTrace[i].getClassName()
                            + "#" + stackTrace[i].getMethodName() + "    " + stackTrace[i].getLineNumber() + "\n");
                }
                fw.write("\n");
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //TODO 发送Log
            sendLog();
        }
    }

    /**
     * 发送错误的Log
     *
     * @throws Exception
     */
    private void sendLog() {

    }

    /**
     * 生成文件名称
     *
     * @return
     */
    private String generationCrashLogName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return sdf.format(new Date());
    }

}
